package com.rzico.account.plugin.hxBank;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class QueryStringUtils {

	public static String getQuery(String url, String key) {
		String keyValue = "";
		try {
			Map<String, List<String>> queryStringMap = splitQuery(url);
			List<String> keyValueList = queryStringMap.get(key);
			if (keyValueList == null || keyValueList.size() == 0) {
				keyValue = "";
			} else {
				keyValue = keyValueList.get(0);
			}
		} catch (Exception e) {
			keyValue = "";
		}
		return keyValue;
	}

	public static Map<String, List<String>> splitQuery(String url) throws UnsupportedEncodingException, MalformedURLException {
		URL queryUrl = new URL(URLDecoder.decode(url,"utf-8"));
		final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>();
		final String[] pairs = queryUrl.getQuery().split("&");
		for (String pair : pairs) {
			final int idx = pair.indexOf("=");
			final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
			if (!query_pairs.containsKey(key)) {
				query_pairs.put(key, new LinkedList<String>());
			}
			final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
			query_pairs.get(key).add(value);
		}
		return query_pairs;
	}

	public static String toLikeStr(String str) {
		if (str != null && str.length() > 0) {
			str = str.trim().replace("\\", "\\\\%").replace("%", "\\%").replace("_", "\\_").replace("'", "\\'")
					.replace("+", "\\+");
		}
		return str;
	}

	public static void main(String[] args) {
		System.out.println(toLikeStr("%"));
//		System.err.println(getQuery("https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20161110163838f231619da20804912345&package=1037687096&redirect_url=https%3A%2F%2Fwww.wechatpay.com.cn", "prepay_id"));
	}
}